﻿using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace WindStyle.SPEntity.Converters
{
    public class SPFieldMultiChoiceValueConverter : IValueConverter
    {
        public object ToFieldValue(object value, Type targetType, ConversionContext context)
        {
            var type = value.GetType();
            if (type.IsEnum)
            {
                var result = new SPFieldMultiChoiceValue();
                var choices = value.ToString().Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
                var members = type.GetFields(BindingFlags.Static | BindingFlags.Public);
                foreach (var member in members)
                {
                    var attributes = member.GetCustomAttributes(typeof(Attributes.EnumMemberAttribute), false);
                    if (attributes.Any() && choices.Contains(member.Name))
                    {
                        result.Add((attributes.First() as Attributes.EnumMemberAttribute).Name);
                    }
                }
                return result.ToString();
            }
            return null;
        }

        public object ToPropertyValue(object value, Type targetType, ConversionContext context)
        {
            var choices = (value as string).Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
            if (targetType.IsEnum)
            {
                var result = Convert.ToInt32(Activator.CreateInstance(targetType));
                var members = targetType.GetFields(BindingFlags.Static | BindingFlags.Public);
                foreach (var member in members)
                {
                    var attributes = member.GetCustomAttributes(typeof(Attributes.EnumMemberAttribute), false);
                    if (attributes.Any()
                        && choices.Contains((attributes.First() as Attributes.EnumMemberAttribute).Name))
                        result |= Convert.ToInt32(targetType.InvokeMember(member.Name, System.Reflection.BindingFlags.GetField, null, null, null));
                }
                return Enum.ToObject(targetType, result);
            }
            return null;
        }
    }
}
